/*
 * @Author: zoushiyong
 * @Date: 2018-11-10 11:07:31
 * @Description: ''
 * @Last Modified by: zoushiyong
 * @Last Modified time: 2018-11-26 11:02:12
 * @ToDo: ''
 */
import React from 'react'
import { Form, Select, Input, Button, Modal, Row, Col } from 'antd'
import api from '../../../api/index'
const FormItem = Form.Item
const Option = Select.Option
class AddSubAccount extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      roleData: [],
      roleId: '',
      initRole: ''
    }
    // 增加账户及账户列表渲染
    this.handleSubmit = this.handleSubmit.bind(this)
    // 账户管理与角色管理的tab跳转
    this.addRole = this.addRole.bind(this)
    // 提交时清空表单
    this.onEmpty = this.onEmpty.bind(this)
    // 修改密码成功弹窗
    this.psswordSuccess = this.psswordSuccess.bind(this)
    // 获取下拉框Role
    this.changeRole = this.changeRole.bind(this)
  }
  changeRole (currency) {
    this.setState({
      roleId: currency
    })
  }
  psswordSuccess () {
    Modal.success({
      className: 'passwordOk',
      title: 'Successfully',
      content: "New sub-account added successfully. We'll send the sign-in account and the randomly generated password to the user's email within few minutes"
    })
  }
  onEmpty () {
    this.props.form.resetFields()
  }
  inputSky (rule, value, callbackFun) {
    if (rule.field === 'email') {
      if (value === '') {
        callbackFun('Please input email')
      } else if (!(/^([0-9A-Za-z\-_\.]+)@([0-9a-z]+\.[a-z]{2,3}(\.[a-z]{2})?)$/g).test(value)) {
        callbackFun('Please input valid email address')
      } else {
        callbackFun()
      }
    } else if (rule.field === 'nickName') {
      if (value === '') {
        callbackFun('Please input user name')
      } else if (/^\s+|\s+$/.test(value)) {
        callbackFun('Please input valid user name address')
      } else {
        callbackFun()
      }
    }
  }

  addRole () {
    this.props.hideModal()
    this.props.onChangeTab('2')
    this.props.handleChildChange('2')
  }
  handleSubmit (e) {
    e.preventDefault()
    const hideModal = this.props.hideModal
    this.props.form.validateFields((err, values) => {
      console.log(values, values)
      if (err) return
      let { roleId } = values
      let { roleList } = this.props
      // 当未选择下拉框，给定默认roleid

      if (!this.state.roleId && roleList && roleList.length > 0) {
        roleId = roleList[0].roleId
      }
      console.log('roleId', roleId)
      T.ajax({
        url: api.addSubAccount.path,
        loading: true,
        data: {
          'nickName': values.nickName,
          'email': values.email,
          'roleId': roleId
        }
      }).then(res => {
        if (res.code === 0) {
          this.psswordSuccess()
          this.setState({
            orderList: res.data.rows,
            rowTotal: res.data.rowTotal
          })
        }
        this.props.queryAccount()
      })
      hideModal()
      this.onEmpty()
    })
  }
  render () {
    const { getFieldDecorator } = this.props.form
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      }
    }
    let { roleList } = this.props
    let roleName = ''
    if (roleList && roleList.length > 0) {
      roleName = roleList[0].roleName
    }
    if (!this.props.showModal) {
      this.onEmpty()
    }
    return (
      <div className='antd-input-hand'>
        <Modal
          title='New Sub-account'
          className='add-role'
          visible={this.props.showModal}
          onOk={this.handleSubmit}
          onCancel={this.props.hideModal}
          okText='Confirm'
          cancelText='Cancel'
        >
          <Form>
            <FormItem
              {...formItemLayout}
              label='Sign-in account'
            >
              {getFieldDecorator('email', {
                rules: [{ required: true },
                  {
                    validator: this.inputSky
                  }]
              })(
                <Input placeholder="Please input the user's email address" maxLength='50' />
              )}
            </FormItem>
            <FormItem
              {...formItemLayout}
              label='User'
            >
              {getFieldDecorator('nickName', {
                rules: [{ required: true },
                  {
                    validator: this.inputSky
                  }]
              })(
                <Input placeholder='Please input user name' maxLength='50' className='ps-input' />
              )}
            </FormItem>
            <Row>
              <Col span={3} />
              <Col span={14}>
                <FormItem
                  {...formItemLayout}
                  label='Role'
                >
                  {getFieldDecorator('roleId', {
                    initialValue: roleName,
                    rules: [{ required: true, message: '' }]
                  })(
                    <Select
                      placeholder='Select a option and change input text above'
                      onChange={this.changeRole}
                    >{
                        roleList && roleList.map((item) => (
                          <Option key={item.roleId}>{item.roleName}</Option>
                        ))
                      }
                    </Select>
                  )}
                </FormItem>
              </Col>
              <Col span={2} />
              <Col span={5}>
                <Button className='addrole' type='primary' onClick={this.addRole}>Add Role</Button>
              </Col>
            </Row>
            <FormItem
              wrapperCol={{ span: 12, offset: 5 }}
            />
          </Form>
        </Modal>

      </div>
    )
  }
}

const Estabbish = Form.create()(AddSubAccount)
export default Estabbish
